package cn.orange.ch07_binarytree;

import cn.orange.TreeNode;

/**
 * LC530.二叉搜索树的最小绝对差
 */
public class LC530 {
    private TreeNode prev = null;
    private int ans = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        getMin(root);
        return ans;
    }

    private void getMin(TreeNode root) {
        if (root == null) return;
        getMin(root.left);
        if (prev != null) {
            ans = Math.min(ans, Math.abs(prev.val - root.val));
        }
        prev = root;
        getMin(root.right);
    }

    public static void main(String[] args) {
        LC530 alg = new LC530();
        TreeNode root1 = new TreeNode(4, new TreeNode(2), new TreeNode(6));
        root1.left.left = new TreeNode(1);
        root1.left.right = new TreeNode(3);
        System.out.println(alg.getMinimumDifference(root1));
        TreeNode root2 = new TreeNode(1, new TreeNode(0), new TreeNode(48));
        root2.right.left = new TreeNode(12);
        root2.right.right = new TreeNode(49);
        System.out.println(alg.getMinimumDifference(root2));
    }
}
